import { create } from 'zustand'
import { persist, createJSONStorage } from 'zustand/middleware'
import { type ILoginResponseData } from '@/api/user'

interface IState {
  userInfo: ILoginResponseData | null
  token: string
  setUserInfo: (params: ILoginResponseData) => void
  setToken: (token: string) => void
  removeToken: () => void
}

const useUserStore = create<IState, [['zustand/persist', IState]]>(
  persist(
    (set) => ({
      userInfo: null,
      token: '',
      setUserInfo: (userInfo: ILoginResponseData) =>
        set(() => ({ userInfo: userInfo })),
      setToken: (token: string) => set(() => ({ token: token })),
      removeToken: () =>
        set(() => ({
          userInfo: null,
          token: ''
        }))
    }),
    { name: 'user', storage: createJSONStorage(() => sessionStorage) }
  )
)

export default useUserStore
